"""
2048游戏核心算法
"""


# 练习１：零元素移至末尾
# 　　[2,0,2,0]  --> [2,2,0,0]
#    [2,0,0,2]  --> [2,2,0,0]
#    [2,4,0,2]  --> [2,4,2,0]
# def zero_to_end():
# 思想：从后向前，如果发现零元素，删除并追加.


def zero_to_end(list_merge):
    """
    零元素移动到末尾
   """
    for i in range(0, len(list_merge)):
        if list_merge[i] == 0:
            list_merge.remove(list_merge[i])
            list_merge.append(0)


# 练习2：将相同数字合并
# 　　[2,2,0,0]  --> [4,0,0,0]
#    [2,0,0,2]  --> [4,0,0,0]
#    [2,0,4,0]  --> [2,4,0,0]
#    [2,2,2,2]  --> [4,4,0,0]
#    [2,2,2,0]  --> [4,2,0,0]
# 先将中间的零元素移到末尾
# 再合并相邻相同元素


def merge(list_merge):
    """
    合并相同
    """
    zero_to_end(list_merge)
    for i in range(len(list_merge) - 1):
        if list_merge[i] != 0 and list_merge[i] == list_merge[i + 1]:
            list_merge[i] = list_merge[i] + list_merge[i + 1]
            del list_merge[i + 1]
            list_merge.append(0)


# 练习3:地图向左移动
map01 = [
    [2, 0, 0, 2],
    [4, 4, 2, 2],
    [2, 4, 0, 4],
    [0, 0, 2, 2],
]


def move_left():
    """
    向左移动
    :return:
    """
    for i in map01:
        merge(i)


move_left()
print(map01)


def move_right():
    """
    向右移动
    :return:
    """
    for i in map01:
        merge(i[::-1])
         while 0 in i:
            i.remove(0)
        while len(i) < 4:
            i.insert(-len(i) - 1, 0)


move_right()
print(map01)


def move_up():
    """
    上移
    :return:
    """
    for num in range(0, 4):
        i = [map01[0][num], map01[1][num], map01[2][num], map01[3][num]]
        merge(i)
        map01[0][num], map01[1][num], map01[2][num], map01[3][num] = i[0], i[1], i[2], i[3]


move_up()
print(map01)


def move_down():
    """
    下移
    :return:
    """
    for num in range(0, 4):
        i = [map01[0][num], map01[1][num], map01[2][num], map01[3][num]]
        merge(i[::-1])
        while 0 in i:
            i.remove(0)
        while len(i) < 4:
            i.insert(-len(i) - 1, 0)
        map01[0][num], map01[1][num], map01[2][num], map01[3][num] = i[0], i[1], i[2], i[3]


move_down()
print(map01)
